package com.android.yinghebike.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.baselibrary.dialog.Comm_DialogFragment;
import com.android.baselibrary.interface_.CommCallBack;
import com.android.baselibrary.tool.CommLoading;
import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.baselibrary.tool.SPUtil;
import com.android.baselibrary.tool.XXPermisionUtil;
import com.android.baselibrary.util.Util;
import com.android.baselibrary.view.Comm_HeadView;
import com.android.baselibrary.view.MultiStateView;
import com.android.yinghebike.R;
import com.android.yinghebike.adapter.BlueToothListAdapter;
import com.android.yinghebike.constants.SPConstants;
import com.android.yinghebike.manager.BleManager;
import com.android.yinghebike.utils.Utils;
import com.hjq.permissions.OnPermissionCallback;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.wandersnail.ble.Device;
import cn.wandersnail.ble.EasyBLE;
import cn.wandersnail.ble.EventObserver;
import cn.wandersnail.ble.callback.ScanListener;

public class Device_ListActivity extends BaseActivity {

    @BindView(R.id.multiplestatusView)
    MultiStateView multiplestatusView;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;
    @BindView(R.id.comm_title)
    Comm_HeadView comm_title;
    @BindView(R.id.iv_loading)
    ImageView iv_loading;

    BlueToothListAdapter adapter;

    List<Device> deviceList = new ArrayList<>();
    Device info;
    int time  =0 ;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_devicelist;
    }

    @Override
    protected void initView() {
        comm_title.setTitle(getString(R.string.device_connect));

        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new BlueToothListAdapter(mContext, callBack);
        recyclerview.setAdapter(adapter);
        adapter.setData(deviceList);

        smartrefreshlayout.setEnableLoadMore(false);
        smartrefreshlayout.setEnableRefresh(false);

        EasyBLE.getInstance().registerObserver(eventObserver);

        Log.i("isLocationEnabled:"+Utils.isLocationEnabled(mContext) );
        if(!Utils.isLocationEnabled(mContext))
        {
            Comm_DialogFragment.showCommDialog(this, "", getString(R.string.device_location_tips), getString(R.string.device_location_ok), getString(R.string.comm_btn_cancel), new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                    finish();
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EasyBLE.getInstance().unregisterObserver(eventObserver);
    }

    //蓝牙事件
    EventObserver eventObserver =  new EventObserver() {
        @Override
        public void onConnectionStateChanged(@NonNull Device device) {
            EventObserver.super.onConnectionStateChanged(device);
            switch (device.getConnectionState()) {
                case SCANNING_FOR_RECONNECTION:

                    break;
                case CONNECTING:
                    Log.i("连接中...");
                    CommLoading.showLoading((FragmentActivity) mContext);
                    break;
                case DISCONNECTED:
                    Log.i("连接失败");
                    time++;
                    if(time==3)
                    {
                        CommLoading.dismissLoading();
                        CommToast.showToast(mContext,"连接失败，请重试");
                        refreshData();
                    }
                    else
                    {
                        BleManager.getInstance().connect(info);
                    }
                    break;
                case SERVICE_DISCOVERED:
                    Log.i("连接成功");
                    CommLoading.dismissLoading();
                    finish();
                    break;
            }
        }
    };

    //点击事件回调
    CommCallBack callBack = new CommCallBack() {
        @Override
        public void onResult(Object obj) {
            info = (Device) obj;
            BleManager.getInstance().disConnect();  //先断开已连接的设备
            BleManager.getInstance().connect(info);
        }
    };



    @Override
    protected void initData() {
        EasyBLE.getInstance().addScanListener(scanListener);
        List<String> permission = getNeedPermissions();
        XXPermisionUtil.requstPermision(mContext, new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {
                refreshData();
            }
        }, permission.toArray(new String[permission.size()]));
    }

    private final ScanListener scanListener = new ScanListener() {
        @Override
        public void onScanStart() {
            Log.i("test", "开始扫描");
            rotate();
        }

        @Override
        public void onScanStop() {
            Log.i("test", "结束扫描");
            stopRotate();
        }

        @Override
        public void onScanResult(@NonNull Device device, boolean isConnectedBySys) {
            if (TextUtils.isEmpty(device.getName())) return;
            boolean has = false;
            for (int i = 0; i < deviceList.size(); i++) {
                if (deviceList.get(i).getName().equals(device.getName())) {
                    has = true;
                }
            }
            if (!has) {
                deviceList.add(device);
                adapter.notifyDataSetChanged();
                Log.i("扫描到设备：" + device.getName());
            }
        }

        @Override
        public void onScanError(int errorCode, @NotNull String errorMsg) {
            switch (errorCode) {
                case ScanListener.ERROR_LACK_LOCATION_PERMISSION://缺少定位权限
                    // ToastUtils.showShort("缺少定位权限");
                    break;
                case ScanListener.ERROR_LOCATION_SERVICE_CLOSED://位置服务未开启
                    //               ToastUtils.showShort("位置服务未开启");
                    break;
                case ScanListener.ERROR_LACK_SCAN_PERMISSION://缺少搜索权限
                    //  ToastUtils.showShort("缺少搜索权限");
                    break;
                case ScanListener.ERROR_LACK_CONNECT_PERMISSION://缺少连接权限
                    //  ToastUtils.showShort("缺少连接权限");
                    break;
                case ScanListener.ERROR_SCAN_FAILED://搜索失败
                    //   ToastUtils.showShort("搜索出错：" + errorCode);
                    break;
            }
            Log.i("errorCode:" + errorCode);
        }
    };

    //刷新数据
    private void refreshData() {
        deviceList.clear();
        adapter.notifyDataSetChanged();

        if (EasyBLE.getInstance().isInitialized()) {
            EasyBLE.getInstance().scanConfiguration.setScanPeriodMillis(60 * 1000);
            if (EasyBLE.getInstance().isScanning()) {
                EasyBLE.getInstance().stopScanQuietly();
            }
            EasyBLE.getInstance().startScan();
        }
    }

    //需要进行检测的权限
    private List<String> getNeedPermissions() {
        List<String> list = new ArrayList<>();
        //target sdk版本在29以上的需要精确定位权限才能搜索到蓝牙设备
        if (getApplicationInfo().targetSdkVersion >= 29) {
            list.add(Manifest.permission.ACCESS_FINE_LOCATION);
            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        } else {
            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        //Android 12需要
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            list.add(Manifest.permission.BLUETOOTH_SCAN);
            list.add(Manifest.permission.BLUETOOTH_CONNECT);
            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        return list;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EasyBLE.getInstance().isInitialized()) {
            EasyBLE.getInstance().stopScan();
        }
    }

    //点击事件
    @OnClick({R.id.iv_loading})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_loading:
                refreshData();
                break;
        }
    }

    private void rotate() {
        Log.i("开始动画");
        RotateAnimation ra = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        ra.setInterpolator(new LinearInterpolator());
        ra.setRepeatMode(Animation.RESTART);
        ra.setRepeatCount(Animation.INFINITE);
        ra.setDuration(1000);
        iv_loading.startAnimation(ra);
    }

    private void stopRotate() {
        Log.i("结束动画");
        iv_loading.clearAnimation();
    }
}
